import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '../Layout'
import movies from './modules/movies.js'
import cinemas from './modules/cinemas.js'
import cart from './modules/cart.js'
import center from './modules/center.js'
import movieDetail from './modules/movieDetail.js'
import cityselect from './modules/cityselect.js'
import cinemaDetail from './modules/cinemaDetail.js'
import login from './modules/login.js'
import orderDetail from './modules/orderDetail.js'
import userinfo from './modules/userinfo.js'

// 解决路由重定向报错
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err)
}

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Layout,
    redirect: '/movies',
    children: [
      ...movies,
      ...cinemas,
      ...cart,
      ...center,
      ...cityselect,
      ...movieDetail,
      ...cinemaDetail,
      ...login,
      ...orderDetail,
      ...userinfo
    ]
  }
]

const router = new VueRouter({
  routes,
  scrollBehavior(to, from, savedPosition) {
    // keep-alive 返回缓存页面后记录浏览位置
    console.log(savedPosition)
    if (savedPosition) {
      window.scrollTo(savedPosition.x, savedPosition.y)
      return savedPosition
    } else {
      return { x: 0, y: 0 }
    }
  }
})

router.beforeEach((to, from, next) => {
  next()
})

export default router
